package com.fwh.web.utils;

import cn.hutool.core.util.StrUtil;

import javax.servlet.http.HttpServletRequest;

/**
*IP获取工具类 
* @ClassName: RequestUtil 
* @Description: TODO 
* @author Comsys-zhangq
* @date 2019年1月7日 下午4:31:44 
*
 */
public class RequestUtil {

	
	private static final String UNKNOWN = "unknown";
	private static final String COMMA = ",";
	
	/**
	 * 获取请求IP
	 * @param request
	 * @return
	 */
	public static String getRequestIP(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		// logger.info("x-forwarded-for:"+ip);
		
		if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
			// logger.info("Proxy-Client-IP:"+ip);
		}

		if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
			// logger.info("WL-Proxy-Client-IP:"+ip);
		}

		if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getHeader("http_client_ip");
			// logger.info("http_client_ip:"+ip);
		}

		if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
			// logger.info("HTTP_X_FORWARDED_FOR:"+ip);
		}

		if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getHeader("x-real-ip");
			// logger.info("x-real-ip:"+ip);
		}

		if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
			// logger.info("getRemoteAddr:"+ip);
		}

		// 如果是多级代理，那么取第一个ip为客户ip
		if (ip != null && ip.indexOf(COMMA) != -1) {
			String[] ips = ip.split(COMMA);
			for (String iptmp : ips) {
				if (!"unknown".equalsIgnoreCase(iptmp)) {
					ip = iptmp;
					break;
				}
			}
		}
		return (StrUtil.isBlank(ip) || "0:0:0:0:0:0:0:1".equals(ip)) ? "127.0.0.1" : ip;
	}
}
